package models

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"sync"
	"time"
)

// Notice 公告模型
type Notice struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	Content   string    `json:"content"`
	Author    string    `json:"author"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

// NoticeService 提供公告的存储和检索功能
type NoticeService struct {
	filePath string
	mutex    sync.RWMutex
}

// NewNoticeService 创建一个新的公告服务
func NewNoticeService(dataDir string) (*NoticeService, error) {
	// 确保目录存在
	if err := os.MkdirAll(dataDir, 0755); err != nil {
		return nil, err
	}

	filePath := filepath.Join(dataDir, "notices.json")

	// 如果文件不存在，创建一个空的公告文件
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		emptyNotices, _ := json.Marshal([]Notice{})
		if err := ioutil.WriteFile(filePath, emptyNotices, 0644); err != nil {
			return nil, err
		}
	}

	return &NoticeService{
		filePath: filePath,
	}, nil
}

// GetAllNotices 获取所有公告
func (s *NoticeService) GetAllNotices() ([]Notice, error) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	data, err := ioutil.ReadFile(s.filePath)
	if err != nil {
		return nil, err
	}

	var notices []Notice
	if err := json.Unmarshal(data, &notices); err != nil {
		return nil, err
	}

	return notices, nil
}

// GetNoticeByID 根据ID获取公告
func (s *NoticeService) GetNoticeByID(id string) (*Notice, error) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	data, err := ioutil.ReadFile(s.filePath)
	if err != nil {
		return nil, err
	}

	var notices []Notice
	if err := json.Unmarshal(data, &notices); err != nil {
		return nil, err
	}

	for _, notice := range notices {
		if notice.ID == id {
			return &notice, nil
		}
	}

	return nil, nil // 没有找到
}

// SaveNotice 保存公告（创建或更新）
func (s *NoticeService) SaveNotice(notice Notice) error {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	data, err := ioutil.ReadFile(s.filePath)
	if err != nil {
		return err
	}

	var notices []Notice
	if err := json.Unmarshal(data, &notices); err != nil {
		return err
	}

	// 如果是新公告，生成ID并添加
	isNew := true
	for i, n := range notices {
		if n.ID == notice.ID {
			// 在更新时保留原有的创建时间
			notice.CreatedAt = n.CreatedAt
			notices[i] = notice
			isNew = false
			break
		}
	}

	if isNew {
		if notice.ID == "" {
			notice.ID = time.Now().Format("20060102150405")
		}
		// 对于新公告，设置创建时间
		if notice.CreatedAt.IsZero() {
			notice.CreatedAt = time.Now()
		}
	}

	// 打印一下公告的创建时间，用于调试
	fmt.Printf("Saving notice [ID: %s] with CreatedAt: %v\n", notice.ID, notice.CreatedAt)

	if isNew {
		notices = append(notices, notice)
	}

	// 保存回文件
	updatedData, err := json.MarshalIndent(notices, "", "  ")
	if err != nil {
		return err
	}

	return ioutil.WriteFile(s.filePath, updatedData, 0644)
}

// DeleteNotice 删除公告
func (s *NoticeService) DeleteNotice(id string) error {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	data, err := ioutil.ReadFile(s.filePath)
	if err != nil {
		return err
	}

	var notices []Notice
	if err := json.Unmarshal(data, &notices); err != nil {
		return err
	}

	// 过滤掉要删除的公告
	var filtered []Notice
	for _, notice := range notices {
		if notice.ID != id {
			filtered = append(filtered, notice)
		}
	}

	// 保存回文件
	updatedData, err := json.MarshalIndent(filtered, "", "  ")
	if err != nil {
		return err
	}

	return ioutil.WriteFile(s.filePath, updatedData, 0644)
}
